package com.tyfspring.beans.strategy;

import com.tyfspring.beans.config.BeanDefinition;
import com.tyfspring.beans.exception.BeansException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @Description 简单的bean实例化策略
 * @Author shallow
 * @Date 2023/3/27 16:14
 */

public class SimpleInstantiationStrategy implements InstantiationStrategy{


    /**
     * jdk反射实例化
     * @param beanDefinition
     * @param beanName
     * @param constructor
     * @param args
     * @return
     * @throws BeansException
     */
    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor constructor, Object[] args) throws BeansException {
        Class beanClass = beanDefinition.getBeanClass();
        try {
            if(null != constructor){
                return beanClass.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            }else{
                return beanClass.getDeclaredConstructor().newInstance();
            }
        } catch (InstantiationException|IllegalAccessException|InvocationTargetException|NoSuchMethodException e) {
            throw new BeansException("Failed to instantiate [" + beanClass.getName() + "]", e);
        }
    }
}
